<?php

namespace Admin\Api\Controllers;

use Admin\Models\device\XhsysDeviceSignIn;
use Admin\Models\device\XhsysAccountdevicelocked;
use Admin\Models\faq\XhfaqInfo;
use Admin\Models\res\XhresArticlePub;
use Admin\Models\user\XhsysUser;
use Admin\Models\school\XhschoolInfo;
use Helpers\Main;
use Helpers\Tool;
use Modules\Ims;
use Phalcon\Paginator\Adapter\QueryBuilder;

class InfoController extends ControllerBase
{

    /**
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170808
     * modify by ck 20171228    添加状态筛选
     *
     * @SWG\Get(
     *     path="/api/info/school",
     *     tags={"Info"},
     *     summary="获取学校列表",
     *     description="",
     *     @SWG\Parameter(name="keyword", in="query", description="关键字", type="string"),
     *     @SWG\Parameter(name="status", in="query", type="integer", enum={0,1,2,3,4},
     *          description="状态(0=未上线，1=上线，2=运营，3=停运，4=测试)",
     *     ),
     *     @SWG\Parameter(name="size", in="query", description="最大数量（默认全部）", type="integer"),
     *     @SWG\Response(response=200, description="获取列表成功",
     *          @SWG\Schema(
     *              type="array",
     *              @SWG\Items(ref="#/definitions/SchoolInfo"),
     *          )
     *     ),
     *     @SWG\Response(response="500", ref="#/responses/Error"),
     * )
     */
    public function schoolAction()
    {
        if (!$this->request->isGet()) {
            return $this->sendErrorResponse(500, '请求方式不正确！');
        }
        $keyword = $this->request->getQuery('keyword', 'string');
        $status = $this->request->getQuery('status', 'int');
        $size = $this->request->getQuery('size', 'int');
        try {
            $query = XhschoolInfo::query()
                ->columns(['iSchoolId AS schoolId', 'sSchoolName AS schoolName'])
                ->where('bDelete = 0');
            if ($keyword) {
                $query = $query->andWhere('sSchoolName like :keyword:', ['keyword' => "%{$keyword}%"]);
            }
            if ($status != '') {
                $query = $query->andWhere('iStatus = :status:', ['status' => $status]);
            }
            if ($size) {
                $query->limit($size);
            }
            $schoolInfo = $query->execute();
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
        return $this->sendJsonResponse($schoolInfo);
    }

    /**
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170807
     * modify by ck 20170808    学校信息从缓存获取
     *
     * @SWG\Get(
     *     path="/api/info/schoolInId",
     *     tags={"Info"},
     *     summary="根据学校id获取信息",
     *     description="",
     *     @SWG\Parameter(name="schoolIds", in="query", description="学校id，逗号分隔", required=true, type="string"),
     *     @SWG\Response(response=200, description="获取列表成功",
     *         @SWG\Schema(
     *             type="array",
     *             @SWG\Items(ref="#/definitions/SchoolInfo")
     *         ),
     *     ),
     *     @SWG\Response(response="400", ref="#/responses/Error"),
     *     @SWG\Response(response="500", ref="#/responses/Error"),
     * )
     */
    public function schoolInIdAction()
    {
        if (!$this->request->isGet()) {
            return $this->sendErrorResponse(500, '请求方式不正确！');
        }
        $schoolIds = array_filter(explode(',', $this->request->getQuery('schoolId', 'string')));
        if (!$schoolIds) {
            return $this->sendErrorResponse(400, '学校ID不能为空！');
        }
        $schoolInfo = [];
        $schoolArr = XhschoolInfo::getSchoolArray();
        foreach ($schoolIds as $schoolId) {
            if (isset($schoolArr[$schoolId])) {
                $schoolInfo[] = ['schoolId' => $schoolId, 'schoolName' => $schoolArr[$schoolId]];
            }
        }
        if (!$schoolInfo) {
            return $this->sendErrorResponse(400, '无学校信息！');
        }
        return $this->sendJsonResponse($schoolInfo);
    }

    /**
     * @param null $schoolId
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170821
     *
     * @SWG\Get(
     *     path="/api/info/schoolClass/{schoolId}",
     *     tags={"Info"},
     *     summary="根据学校id获取行政班列表",
     *     description="",
     *     @SWG\Parameter(name="schoolId", in="path", description="学校id", required=true, type="integer"),
     *     @SWG\Response(response=200, description="获取列表成功",
     *         @SWG\Schema(
     *             type="array",
     *             @SWG\Items(
     *                 @SWG\Property(property="adClaName", description="行政班名称", type="string"),
     *             )
     *         ),
     *     ),
     *     @SWG\Response(response="400", ref="#/responses/Error"),
     *     @SWG\Response(response="500", ref="#/responses/Error"),
     * )
     */
    public function schoolClassAction($schoolId = null)
    {
        if (!$this->request->isGet()) {
            return $this->sendErrorResponse(500, '请求方式不正确！');
        }
        if (!$schoolId) {
            return $this->sendErrorResponse(400, '学校ID不能为空！');
        }
        $classList = XhsysUser::find([
            'columns' => 'sAdClsName AS adClaName',
//            'conditions' => 'iSchoolId = :schoolId: AND bDelete = 0 AND sAdClsName <> "" AND bHistory = 0 AND bCompany = 0 AND bDisable = 0',
            'conditions' => 'iSchoolId = :schoolId: AND bDelete = 0 AND sAdClsName <> "" AND bHistory = 0 AND bDisable = 0',
            'group' => 'sAdClsName',
            'bind' => ['schoolId' => $schoolId]
        ]);
        if (!$classList) {
            return $this->sendErrorResponse(400, '无班级信息！');
        }
        $classList = $classList->toArray();
        return $this->sendJsonResponse($classList);
    }

    /**
     * @param null $schoolId
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170907
     *
     * @SWG\Get(
     *     path="/api/info/schoolTchBook/{schoolId}",
     *     tags={"Info"},
     *     summary="根据学校id获取教师及教辅书列表",
     *     description="",
     *     @SWG\Parameter(name="schoolId", in="path", description="学校id", required=true, type="integer"),
     *     @SWG\Response(response=200, description="获取列表成功",
     *         @SWG\Schema(
     *             type="array",
     *             @SWG\Items(
     *                 @SWG\Property(property="tchId", description="教师id", type="string"),
     *                 @SWG\Property(property="tchName", description="教师姓名", type="string"),
     *                 @SWG\Property(
     *                      property="books",
     *                      description="教辅书列表",
     *                      type="array",
     *                      @SWG\Items(
     *                          @SWG\Property(property="bookName", description="教辅书名", type="string"),
     *                      )
     *                  ),
     *             )
     *         ),
     *     ),
     *     @SWG\Response(response="400", ref="#/responses/Error"),
     *     @SWG\Response(response="500", ref="#/responses/Error"),
     * )
     */
    public function schoolTchBookAction($schoolId = null)
    {
        if (!$this->request->isGet()) {
            return $this->sendErrorResponse(500, '请求方式不正确！');
        }
        if (!$schoolId) {
            return $this->sendErrorResponse(400, '学校ID不能为空！');
        }
        try {
            $dbName = null;
            $db = Main::getSchoolMainDB($schoolId, $dbName);
            if (!$db) {
                throw new \Exception('学校数据库连接失败');
            }
            //获取默认期次
            $sql = 'SELECT sy_id FROM system_type
  WHERE sy_type = "kkqcsz" AND sy_state = 0 AND sy_name2 = 1 ORDER BY sy_ord';
            $termId = $db->fetchOne($sql);
            $termId = $termId['sy_id'];
            if (!$termId) {
                throw new \Exception('获取默认期次失败');
            }
            $sql = "SELECT co_id,cl_id,te_us_id,( SELECT us_name FROM users WHERE us_id = te_us_id ) AS te_us_name
  FROM attendclass_time_class, teacher_list, course_list, class_list WHERE cl_at_id = at_id AND at_qc_id = '{$termId}'
  AND co_id = te_co_id AND te_flag = 0 AND cl_flag = 1 AND cl_id = te_cl_id AND co_coach_flag = '0' AND co_typeflag = 1
  GROUP BY co_id, cl_id ORDER BY co_ord";
            $tchInfo = $db->fetchAll($sql);
            if (empty($tchInfo)) {
                throw new \Exception('获取教师开课列表失败');
            }
            $tchIds = array_column($tchInfo, 'te_us_id');
            $tchIds = implode(',', $tchIds);
            $sql = "select tr_name,tk_us_id,tr_id,tr_source_tr_id from tk_power,tree_homework_list
  where (tk_tr_id=tr_id and tk_us_id in ({$tchIds}) and  tr_id<>0) order by tk_ord desc";
            $bookInfo = $db->fetchAll($sql);
            if (empty($bookInfo)) {
                throw new \Exception('获取教师教辅书列表失败');
            }
            $tchBook = [];
            foreach ($tchInfo as $row) {
                $tchBook[$row['te_us_id']] = ['tchId' => $row['te_us_id'], 'tchName' => $row['te_us_name']];
            }
            foreach ($bookInfo as $row) {
                if (!isset($tchBook[$row['tk_us_id']])) {
                    continue;
                }
                $tchBook[$row['tk_us_id']]['books'][] = ['bookName' => $row['tr_name']];
            }
            return $this->sendJsonResponse(array_values($tchBook));
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }


    /**
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20180412
     * modify by dale 20180418  添加地址前缀判断 如果不包含前缀 一律使用http
     *
     * @SWG\Get(
     *     path="/api/info/whiteSites",
     *     tags={"Info"},
     *     summary="获取浏览器白名单",
     *     description="",
     *     @SWG\Parameter(name="schoolId", in="query", description="学校id", required=true, type="integer"),
     *     @SWG\Response(response=200, description="获取浏览器白名单成功",
     *         @SWG\Schema(
     *             type="array",
     *             @SWG\Items(
     *                 @SWG\Property(property="schoolId", description="学校id", type="integer"),
     *                 @SWG\Property(property="createId", description="创建人id", type="integer"),
     *                 @SWG\Property(property="siteName", description="网站名称", type="string"),
     *                 @SWG\Property(property="url", description="网站地址", type="string"),
     *                 @SWG\Property(property="coverUrl", description="封面地址", type="string"),
     *                 @SWG\Property(property="startTime", description="开始时间", type="string"),
     *                 @SWG\Property(property="endTime", description="结束时间", type="string"),
     *                 @SWG\Property(property="isLong", description="监听类型(1=永久，2=实时)", type="integer",enum={1,2}),
     *                 @SWG\Property(property="isShow", description="是否展示(1=是，2=否)", type="integer",enum={1,2}),
     *             )
     *         ),
     *     ),
     *     @SWG\Response(response="400", ref="#/responses/Error"),
     *     @SWG\Response(response="500", ref="#/responses/Error"),
     * )
     */
    public function whiteSitesAction()
    {
        try {
            $schoolId = $this->request->getQuery('schoolId', 'int');
            $userId = $this->request->getQuery('userId', 'int');
            if (!$schoolId) {
                return $this->sendErrorResponse(400, '缺少学校id');
            }
            $builder = $this->modelsManager->createBuilder()
                ->columns('iSchoolId as schoolId,iCreateUserId as createId,sSiteName as siteName,
                sUrl as url , tStartTime as startTime , tEndTime as endTime , bLong as isLong ,sImage as coverUrl,
                bShow as isShow ')
                ->from('Admin\\Models\\school\\XhschoolSite')
                ->where('bDelete = 0 ');
            if ($schoolId) {
                $builder->andWhere('iSchoolId = :schoolId: or bCommon = 1', ['schoolId' => $schoolId]);
            }
            if ($userId) {
                $builder->andWhere('iCreateUserId = :userId:', ['userId' => $userId]);
            }
            $data = $builder->getQuery()->execute()->toArray();

            foreach ($data as $index => &$row) {
                if (!preg_match('/(http:\/\/)|(https:\/\/)/i', $row['url'])) { //判断是否包含http、https前缀
                    $row['url'] = 'http://' . $row['url'];
                }
            }
            unset($row);
            return $this->sendJsonResponse($data);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(400, $e->getMessage());
        }
    }

    /**
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180823
     *
     * @SWG\Get(
     *     path="/api/info/faq",
     *     tags={"Info"},
     *     summary="获取faq列表",
     *     description="",
     *     @SWG\Parameter(name="appCode", in="query", description="应用编号", required=false, type="string"),
     *     @SWG\Parameter(name="public", in="query", description="是否公开", required=false, type="boolean", default=true),
     *     @SWG\Parameter(name="userType", in="query", required=false, type="integer",
     *          description="用户类型。1=学生,2=教师,3=家长,4=通用",
     *     ),
     *     @SWG\Parameter(name="target", in="query", required=false, type="integer", default="1", enum={1,2},
     *          description="目标。1=常见问题,2=使用说明",
     *     ),
     *     @SWG\Response(response=200, description="获取列表成功",
     *         @SWG\Schema(
     *             type="array",
     *             @SWG\Items(
     *                 @SWG\Property(property="id", description="id", type="integer"),
     *                 @SWG\Property(property="appCode", description="应用编号", type="string"),
     *                 @SWG\Property(property="question", description="提问", type="string"),
     *                 @SWG\Property(property="answer", description="回答", type="string"),
     *                 @SWG\Property(property="public", description="是否公开", type="boolean"),
     *                 @SWG\Property(property="target", description="目标", type="integer"),
     *                 @SWG\Property(property="userType", description="用户类型", type="integer")
     *             )
     *         ),
     *     ),
     *     @SWG\Response(response="400", ref="#/responses/Error"),
     *     @SWG\Response(response="500", ref="#/responses/Error"),
     * )
     */
    public function faqAction()
    {
        $appCode = $this->request->getQuery('appCode', 'string');
        $public = $this->request->getQuery('public', 'string', 'true') == 'true';
        $userType = $this->request->getQuery('userType', 'int');
        $target = $this->request->getQuery('target', 'int', 1);
        try {
            $params = [
                'columns' => 'iFAQId as id,iAppCode as appCode, sQuestion as question, mAnswer as answer,
                bPublic as public, iUserType as userType, iTarget as target',
                'conditions' => 'bDelete = 0 AND bPublic = :public:',
                'bind' => ['public' => intval($public)],
                'order' => 'iOrderCode'
            ];
            if ($appCode) {
                $params['conditions'] .= ' AND iAppCode = :appCode:';
                $params['bind']['appCode'] = $appCode;
            }
            if ($userType) {
                $params['conditions'] .= ' AND iUserType = :userType:';
                $params['bind']['userType'] = $userType;
            }
            if ($target) {
                $params['conditions'] .= ' AND iTarget = :target:';
                $params['bind']['target'] = $target;
            }
            $data = XhfaqInfo::find($params)->toArray();
            Tool::runInteger($data, ['id', 'userType', 'target']);
            Tool::runEnum($data, ['public' => [0 => false, 1 => true]]);
            return $this->sendJsonResponse($data);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, '获取列表失败', $e->getMessage());
        }
    }


    /**
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20180816
     *
     * @SWG\Get(
     *     path="/api/info/ztNews",
     *     tags={"Info"},
     *     summary="获取智通新闻",
     *     description="",
     *     @SWG\Parameter(name="column", in="query", description="栏目id(1=学海新闻，2=活动资讯，3=媒体报道)", required=false, type="integer",enum={1,2,3}),
     *     @SWG\Parameter(name="key", in="query", description="关键字", required=false, type="string"),
     *     @SWG\Parameter(name="page", in="query", description="页码,从1开始", required=false, type="integer", default="1"),
     *     @SWG\Parameter(name="size", in="query", description="行数", required=false, type="integer", default="6"),
     *     @SWG\Response(response=200, description="获取列表成功",
     *         @SWG\Schema(
     *             type="array",
     *             @SWG\Items(
     *                 @SWG\Property(property="id", description="新闻id", type="integer"),
     *                 @SWG\Property(property="title", description="文章标题", type="string"),
     *                 @SWG\Property(property="content", description="文章内容", type="string"),
     *                 @SWG\Property(property="coverUrl", description="封面", type="string"),
     *                 @SWG\Property(property="coverMobile", description="手机端封面", type="string"),
     *                 @SWG\Property(property="isTop", description="是否置顶", type="integer"),
     *                 @SWG\Property(property="column", description="新闻类型(1=学海新闻，2=活动资讯，3=媒体报道)", type="integer",enum={1,2,3}),
     *                 @SWG\Property(property="publicTime", description="发布时间(时间戳到秒)", type="integer"),
     *             )
     *         ),
     *     ),
     *     @SWG\Response(response="400", ref="#/responses/Error"),
     *     @SWG\Response(response="500", ref="#/responses/Error"),
     * )
     */
    public function ztNewsAction()
    {
        try {
            $column = $this->request->getQuery('column', 'int', 0);
            $key = $this->request->getQuery('key', 'string', '');
            $page = $this->request->getQuery('page', 'int', 1);                     //获取页码，默认1
            $size = $this->request->getQuery('size', 'int', 8);
            $builder = $this->modelsManager->createBuilder()
                ->columns('a.iArtId as id,a.sTitle as title ,a.mText as content,p.sCoverUrl as coverUrl,p.sCoverMobile as coverMobile,p.bTop as isTop,p.iColumn as column,p.iPublicTime as publicTime')
                ->from(['p' => 'Admin\Models\res\XhresArticlePub'])
                ->leftJoin('Admin\Models\res\XhresArticle', 'a.iArtId = p.iArtId', 'a')
//                ->from(['a' => 'Admin\Models\res\XhresArticle'])
//                ->leftJoin('Admin\Models\res\XhresArticlePub', 'a.iArtId = p.iArtId', 'p')
                ->where('a.bDelete = 0 and a.iArtType = 10 and p.bShow = 1 ')
                ->orderBy('iPublicTime desc');
//            $newColumns = [1 => '学海新闻', 2  => '活动资讯', 3 => '媒体报道'];
            if ($key) {
                $builder->andWhere('a.sTitle like :key:', ['key' => '%' . $key . '%']);
            }
            if ($column) {
                $builder->andWhere('p.iColumn = :iColumn:', ['iColumn' => $column]);
            }
            $paginate = new QueryBuilder([
                'builder' => $builder,
                'limit' => $size,
                'page' => $page,
            ]);
            $result = $paginate->getPaginate();
            $data = [
                'page' => $result->current,
                'size' => $result->limit,
                'totalPage' => $result->total_pages,
                'total' => $result->total_items,
                'rows' => $result->items->toArray()
            ];
            return $this->sendJsonResponse($data);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20180816
     *
     * @SWG\Get(
     *     path="/api/info/getZTNewsDetail",
     *     tags={"Info"},
     *     summary="获取智通新闻详情",
     *     description="",
     *     @SWG\Parameter(name="id", in="query", description="文章id", required=false, type="integer"),
     *     @SWG\Parameter(name="isTop", in="query", description="是否获取置顶文章", required=false, type="integer"),
     *     @SWG\Response(response=200, description="获取列表成功",
     *         @SWG\Schema(
     *             type="array",
     *             @SWG\Items(
     *                 @SWG\Property(property="id", description="新闻id", type="integer"),
     *                 @SWG\Property(property="title", description="文章标题", type="string"),
     *                 @SWG\Property(property="content", description="文章内容", type="string"),
     *                 @SWG\Property(property="coverUrl", description="封面", type="string"),
     *                 @SWG\Property(property="coverMobile", description="手机端封面", type="string"),
     *                 @SWG\Property(property="isTop", description="是否置顶", type="integer"),
     *                 @SWG\Property(property="column", description="新闻类型(1=学海新闻，2=活动资讯，3=媒体报道)", type="integer",enum={1,2,3}),
     *                 @SWG\Property(property="publicTime", description="发布时间(时间戳到秒)", type="integer"),
     *             )
     *         ),
     *     ),
     *     @SWG\Response(response="400", ref="#/responses/Error"),
     *     @SWG\Response(response="500", ref="#/responses/Error"),
     * )
     */
    public function getZTNewsDetailAction()
    {
        try {
            $id = $this->request->getQuery('id', 'int');
            $top = $this->request->getQuery('isTop', 'int');
            if (!$id && !$top) {
                return $this->sendErrorResponse(400, '缺少参数');
            }
            $builder = $this->modelsManager->createBuilder()
                ->columns('a.iArtId as id,a.sTitle as title ,a.mText as content,p.sCoverUrl as coverUrl,p.sCoverMobile as coverMobile,p.bTop as isTop,p.iColumn as column,p.iPublicTime as publicTime')
                ->from(['a' => 'Admin\Models\res\XhresArticle'])
                ->leftJoin('Admin\Models\res\XhresArticlePub', 'a.iArtId = p.iArtId', 'p')
                ->where('a.bDelete = 0 and a.iArtType = 10 and bShow = 1 ');
            if (!$top && $id) {
                $builder->andWhere('a.iArtId = :id:', ['id' => $id])->limit(1);
            } elseif ($top) {
                $builder->andWhere('p.bTop = :top:', ['top' => $top]);
            }
            $data = Tool::getValue($builder->getQuery()->execute()->toArray(), 0, []);
            if (!$data) {
                return $this->sendErrorResponse(500, '未找到该文章');
            }
            $numBuilder = $this->modelsManager->createBuilder()
                ->columns('a.iArtId as id,a.sTitle as title')
                ->from(['a' => 'Admin\Models\res\XhresArticle'])
                ->leftJoin('Admin\Models\res\XhresArticlePub', 'a.iArtId = p.iArtId', 'p')
                ->where('a.bDelete = 0 and a.iArtType = 10 and p.bShow = 1')
                ->orderBy('p.iPublicTime desc');
            $prev = clone $numBuilder;
            $prev->andWhere('p.iPublicTime < :iPublicTime: and p.iColumn = :column:', ['iPublicTime' => $data['publicTime'], 'column' => $data['column']]);
            $prev = $prev->limit(1)->getQuery()->execute()->toArray();
            $prev = Tool::getValue($prev, 0, []);
            $next = clone $numBuilder;
            $next->andWhere('p.iPublicTime > :iPublicTime: and p.iColumn = :column:', ['iPublicTime' => $data['publicTime'], 'column' => $data['column']]);
            $next = $next->limit(1)->getQuery()->execute()->toArray();
            $next = Tool::getValue($next, 0, []);
            $data['prev'] = $prev;
            $data['next'] = $next;
            return $this->sendJsonResponse($data);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 获取设备签收状态
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20190125
     *
     * @SWG\Get(
     *     path="/api/info/getSignInStatus",
     *     tags={"Info"},
     *     summary="获取设备签收状态",
     *     description="",
     *     @SWG\Parameter(name="userId", in="query", description="用户id", required=true, type="integer"),
     *     @SWG\Parameter(name="deviceNumber", in="query", description="设备号", required=true, type="string"),
     *     @SWG\Response(response=200, description="获取设备签收状态成功",
     *         @SWG\Schema(
     *              @SWG\Property(property="deviceStatus", description="设备签收状态0未签收1已签收", type="integer"),
     *              @SWG\Property(property="signInStatus", description="签收开关0关1开", type="integer"),
     *              @SWG\Property(property="protocolStatus", description="协议开关0关1开", type="integer"),
     *              @SWG\Property(property="partsStatus", description="配件开关0关1开", type="integer"),
     *         ),
     *     ),
     *     @SWG\Response(response="400", ref="#/responses/Error")
     * )
     */
    public function getSignInStatusAction()
    {
        $userId = $this->request->getQuery('userId', 'int');
        $deviceNumber = $this->request->getQuery('deviceNumber', 'string');
        if (!$userId || !$deviceNumber) {
            return $this->sendErrorResponse(400, '参数错误', '缺少必要参数');
        }
        $findData = XhsysDeviceSignIn::findFirst([
            'columns' => 'iStatus as deviceStatus, iSignInStatus as signInStatus, iProtocolStatus as protocolStatus, iPartsStatus as partsStatus',
            'conditions' => "bDelete = 0 and iUserId = :iUserId: and sDeviceNumber = :sDeviceNumber: and iStatus != 2",
            'bind' => ['iUserId' => $userId, 'sDeviceNumber' => $deviceNumber]
        ]);
        //签收表中找不到，去绑定表查询
        if (!$findData) {
            $findData = XhsysAccountdevicelocked::findFirst([
                'conditions' => 'iUserId = :iUserId: and sDeviceNumber = :sDeviceNumber: and bDelete = 0',
                'bind' => ['iUserId' => $userId, 'sDeviceNumber' => $deviceNumber]
            ]);
            $return = [
                'deviceStatus' => 0,
                'signInStatus' => 0,
                'protocolStatus' => 0,
                'partsStatus' => 0
            ];
            if ($findData) {
                $return['deviceStatus'] = 1;//找到绑定状态为已签收，其他默认为0关
            }
            return $this->sendJsonResponse($return, true);
        } else {
            $findData = $findData->toArray();
        }
        return $this->sendJsonResponse($findData, true);
    }
    /**
     * 签收接口
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20190123
     *
     * @SWG\Post(
     *     path="/api/info/signForDevice",
     *     tags={"Info"},
     *     consumes={"application/json"},
     *     summary="更新签收设备数据接口",
     *     description="更新签收设备数据接口",
     *     @SWG\Parameter(name="body", in="body", description="参数信息", required=true,
     *         @SWG\Schema(
     *              required={"userId", "deviceNumber", "signature", "signatureUrl", "contact", "contactPhoneNumber", "date"},
     *              @SWG\Property(property="userId", description="用户id", type="integer"),
     *              @SWG\Property(property="deviceNumber", description="设备号", type="string"),
     *              @SWG\Property(property="iMei", description="iMei号", type="string"),
     *              @SWG\Property(property="signature", description="签名字符串", type="string"),
     *              @SWG\Property(property="signatureUrl", description="签名地址", type="string"),
     *              @SWG\Property(property="date", description="签收日期", type="string"),
     *              @SWG\Property(property="contact", description="联系人", type="string"),
     *              @SWG\Property(property="contactPhoneNumber", description="联系人手机", type="string"),
     *         )
     *     ),
     *     @SWG\Response(response=200, description="成功",
     *         @SWG\Schema(
     *             required={"code", "msg"},
     *             @SWG\Property(property="code", description="状态码", type="integer"),
     *             @SWG\Property(property="msg", description="成功", type="string"),
     *         ),
     *     ),
     *     @SWG\Response(response="400", ref="#/responses/Error"),
     * )
     *
     */
    public function signForDeviceAction()
    {
        try {
            $request = $this->request->getJsonRawBody(true);
            $userId = isset($request['userId']) ? $request['userId'] : '';
            $deviceNumber = isset($request['deviceNumber']) ? $request['deviceNumber'] : '';
            $iMei = isset($request['iMei']) ? $request['iMei'] : '';
            $signature = isset($request['signature']) ? $request['signature'] : '';//签名字符串
            $signatureUrl = isset($request['signatureUrl']) ? $request['signatureUrl'] : '';////签名url
            $date = isset($request['date']) ? $request['date'] : '';
            $contact = isset($request['contact']) ? $request['contact'] : '';
            $contactPhoneNumber = isset($request['contactPhoneNumber']) ? $request['contactPhoneNumber'] : '';
            if (!$userId || !$deviceNumber || !$signatureUrl || !$date) {
                return $this->sendErrorResponse(400, '参数错误','缺少必要参数');
            }
            $check = $this->checkTel($contactPhoneNumber);
            if (!$check) {
                return $this->sendErrorResponse(400, '参数错误', '联系人手机号不正确');
            }
            $findData = XhsysDeviceSignIn::findFirst([
                'conditions' => "bDelete = 0 and iUserId = :iUserId: and sDeviceNumber = :sDeviceNumber: and (iStatus = 0 or iStatus = 1)",
                'bind' => ['iUserId' => $userId, 'sDeviceNumber' => $deviceNumber],
                'order' => 'iId desc',
            ]);
            if (!$findData) {//没有则新增
                $userData = XhsysUser::findFirst([
                    'columns' => 'iUserId, sLogonName, iSchoolId, sAdClsName',
                    'conditions' => "bDelete = 0 and iUserId = :iUserId:",
                    'bind' => ['iUserId' => $userId]
                ]);
                $findData = new XhsysDeviceSignIn();
                $findData->iUserId = $userId;
                $findData->sLogonName = $userData && $userData->sLogonName ? $userData->sLogonName : '';
                $findData->iSchoolId = $userData && $userData->iSchoolId ? $userData->iSchoolId : '';
                $findData->sAdClsName = $userData && $userData->sAdClsName ? $userData->sAdClsName : '';
                $findData->iSignInStatus = 0;//默认
                $findData->iProtocolStatus = 0;//默认
                $findData->iPartsStatus = 0;//默认
            }
            $findData->iStatus = 1;
            $findData->sDeviceNumber = $deviceNumber;
            $findData->sIMei = $iMei;
            $findData->sSignature = $signature;
            $findData->sSignatureUrl = $signatureUrl;
            $findData->sSignInDate = $date;
            $findData->sContact = $contact;
            $findData->sContactPhone = $contactPhoneNumber;
            if (!$findData->save()) {
                throw new \Exception('保存数据失败');
            }
            return $this->sendSuccessResponse('成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(400, '保存出错', $e->getMessage());
        }
    }

    /**
     * 检测是否正确的手机号,读取配置，如果没有配置则按正则
     *
     * @param $phoneNum
     *
     * @return bool
     *
     * create by qgz 20190220
     */
    public function checkTel($phoneNum)
    {
        if (preg_match("/^1[3456789]\d{9}$/", $phoneNum)) {
            $phoneArr = '130,131,132,133,134,135,136,137,138,139,145,146,147,148,149,150,151,152,153,155,156,157,158,159,165,166,170,171,172,173,174,175,176,177,178,180,181,182,183,184,185,186,187,188,189,191,198,199';
            $phoneArr = explode(',', $phoneArr);
            if (in_array(substr($phoneNum, 0, 3), $phoneArr)) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20190124
     *
     * @SWG\Get(
     *     path="/api/info/getAccessory",
     *     tags={"Info"},
     *     summary="根据商品名称获取配件信息",
     *     description="",
     *     @SWG\Parameter(name="prodName", in="query", description="商品名称", required=true, type="string"),
     *     @SWG\Response(response=200, description="获取配件信息成功",
     *         @SWG\Schema(
     *             type="array",
     *             @SWG\Items(
     *                 @SWG\Property(property="name", description="配件名称", type="string"),
     *                 @SWG\Property(property="num", description="配件数量", type="integer"),
     *             )
     *         ),
     *     ),
     *     @SWG\Response(response="400", ref="#/responses/Error"),
     *     @SWG\Response(response="500", ref="#/responses/Error"),
     * )
     */
    public function getAccessoryAction()
    {
        $prodName = $this->request->getQuery('prodName', 'string');
        if (!$prodName) {
            return $this->sendErrorResponse(400, '缺少要参数');
        }
        try {
            $prodInfo = Ims::getProdInfoByName($prodName);
            if (!is_array($prodInfo['mAccessory'])) {
                $prodInfo['mAccessory'] = $prodInfo['mAccessory'] ? unserialize($prodInfo['mAccessory']) : [];
            }
            return $this->sendJsonResponse($prodInfo['mAccessory']);
        } catch (\Exception $e) {
//            return $this->sendJsonResponse(['code' => 200]);
            return $this->sendErrorResponse(400, $e->getMessage());
        }
    }

}

/**
 * @SWG\Definition(
 *     definition="SchoolInfo",
 *     @SWG\Property(property="schoolId", description="学校id", type="integer"),
 *     @SWG\Property(property="schoolName", description="学校名称", type="string")
 * )
 */